package es.mgil.whoWantsToBeAMillonaire.activities;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import es.mgil.whoWantsToBeAMillonaire.R;
import es.mgil.whoWantsToBeAMillonaire.dialogs.CreditsDialog;
import es.mgil.whoWantsToBeAMillonaire.dialogs.NoUserInfoDialog;
import es.mgil.whoWantsToBeAMillonaire.util.MusicManager;
import es.mgil.whoWantsToBeAMillonaire.util.PreferencesKeys;

public class Main extends FragmentActivity {
	public SharedPreferences preferences;
	private Editor editor;

	private CheckBox music;

	private int lastOrientation;
	private boolean pausable;

	private MusicManager mmMainTheme;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main);

		// store the preferences
		preferences = getSharedPreferences(PreferencesKeys.SHARED_PREFERENCES,
				MODE_PRIVATE);
		editor = preferences.edit();

		// store the current orientation
		lastOrientation = getResources().getConfiguration().orientation;

		// initialize some useful objects from interface
		music = (CheckBox) findViewById(R.id.checkBoxMusic);
		music.setChecked(MusicManager.isMusicEnabled(preferences));

		TextView title = (TextView) findViewById(R.id.TextViewTitle);
		Typeface font = Typeface.createFromAsset(getAssets(),
				"Chantelli_Antiqua.ttf");
		title.setTypeface(font);

		// initialize the music manager for current activity
		mmMainTheme = MusicManager.getInstance(R.raw.main_theme, null, true);
	}

	@Override
	protected void onResume() {
		// check music enablement
		checkMusic();

		super.onResume();
	}

	@Override
	protected void onPause() {
		int orientation = getResources().getConfiguration().orientation;
		if (lastOrientation != orientation) {
			// if onPause is called due to an orientation change, do nothing
			lastOrientation = orientation;
		} else {
			// in other case (i.e. application change...), pause the music
			// normally it's pausable, but it should not be paused if we open
			// Settings or Score activities
			if (pausable) {
				mmMainTheme.pausePlayer();
			}
		}
		super.onPause();
	}

	@Override
	public void finish() {
		// destroy all the players from the music manager
		MusicManager.destroyAllPlayers();

		super.finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_main, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			// show Credits dialog
			CreditsDialog dialog = new CreditsDialog();
			dialog.show(getSupportFragmentManager(),
					CreditsDialog.CREDITS_DIALOG_ID);
			return true;
		default:
			return super.onMenuItemSelected(featureId, item);
		}
	}

	public void startPlay(View view) {
		// if no user name or coordinates are set in Settings activity, can't
		// start playing
		NoUserInfoDialog dialog = null;
		String name = preferences.getString(PreferencesKeys.PREFERENCES_NAME,
				"");
		double longitude = preferences.getFloat(
				PreferencesKeys.PREFERENCES_LONGITUDE, 0);
		double latitude = preferences.getFloat(
				PreferencesKeys.PREFERENCES_LATITUDE, 0);
		if (name.equals("") || longitude == 0 || latitude == 0) {
			dialog = new NoUserInfoDialog();
			dialog.show(getSupportFragmentManager(),
					NoUserInfoDialog.NO_USER_INFO_DIALOG_ID);
			return;
		}

		// before start the activity, restore Play preferences
		editor.remove(PreferencesKeys.PREFERENCES_QUESTION_NUMBER);
		editor.remove(PreferencesKeys.PREFERENCES_PHONE_REMOVED);
		editor.remove(PreferencesKeys.PREFERENCES_PERCENT_REMOVED);
		editor.remove(PreferencesKeys.PREFERENCES_AUDIENCE_REMOVED);
		editor.remove(PreferencesKeys.PREFERENCES_PHONE_USED);
		editor.remove(PreferencesKeys.PREFERENCES_PERCENT_USED);
		editor.remove(PreferencesKeys.PREFERENCES_AUDIENCE_USED);
		editor.remove(PreferencesKeys.PREFERENCES_SELECTED_ANSWER);
		editor.remove(PreferencesKeys.PREFERENCES_FINAL_SCORE);
		editor.remove(PreferencesKeys.PREFERENCES_ERROR);
		editor.remove(PreferencesKeys.PREFERENCES_PROGRESS_BAR_PROGRESS);
		editor.remove(PreferencesKeys.PREFERENCES_PROGRESS_STATE);
		editor.remove(PreferencesKeys.PREFERENCES_QUESTION_MUSIC_PLAYING);

		List<String> toRemove = new ArrayList<String>();
		for (Entry<String, ?> entry : preferences.getAll().entrySet()) {
			if (entry.getKey().contains(PreferencesKeys.PREFERENCES_VISIBLE)
					|| entry.getKey().contains(
							PreferencesKeys.PREFERENCES_CLICKABLE)
					|| entry.getKey().contains(
							PreferencesKeys.PREFERENCES_COLOR)) {
				toRemove.add(entry.getKey());
			}
		}
		for (String pref : toRemove) {
			editor.remove(pref);
		}

		editor.commit();

		// stop the music belong to current activity
		mmMainTheme.stopPlayer();
		startActivity(new Intent(this, Play.class));
	}

	public void startScores(View view) {
		// first time always will be shown Local Scores tab
		editor.putString(PreferencesKeys.PREFERENCES_CURRENT_TAB,
				Scores.LocalTab);
		editor.commit();

		// do the music not pausable, in order to continue it
		pausable = false;
		startActivity(new Intent(this, Scores.class));
	}

	public void startSettings(View view) {
		// do the music not pausable, in order to continue it
		pausable = false;
		startActivity(new Intent(this, Settings.class));
	}

	public void musicEnablement(View view) {
		// toggle music enablement and set it
		MusicManager.setMusicEnablement(editor, music.isChecked());
		checkMusic();
	}

	private void checkMusic() {
		if (MusicManager.isMusicEnabled(preferences)) {
			// if music is enabled, start it if it's not started yet
			mmMainTheme.startPlayer(this);
		} else {
			// stop the music
			mmMainTheme.stopPlayer();
		}

		// do the music pausable as default
		pausable = true;
	}
}
